from nonebot import NoneBot, on_command
from nonebot.adapters.onebot.v11 import Message, MessageSegment, Bot, Event
from nonebot.adapters.onebot.v11.event import GroupMessageEvent, PrivateMessageEvent
from nonebot.rule import to_me
import asyncio

# 初始化机器人
bot = NoneBot()

# 发送私聊消息
async def send_private_message(bot: Bot, user_id: int, message: str):
    """
    发送私聊消息
    :param bot: 机器人实例
    :param user_id: 目标用户QQ号
    :param message: 消息内容
    """
    try:
        await bot.send_private_msg(user_id=user_id, message=message)
        print(f"已向用户 {user_id} 发送消息: {message}")
    except Exception as e:
        print(f"发送私聊消息失败: {str(e)}")

# 发送群消息
async def send_group_message(bot: Bot, group_id: int, message: str):
    """
    发送群消息
    :param bot: 机器人实例
    :param group_id: 目标群号
    :param message: 消息内容
    """
    try:
        await bot.send_group_msg(group_id=group_id, message=message)
        print(f"已向群 {group_id} 发送消息: {message}")
    except Exception as e:
        print(f"发送群消息失败: {str(e)}")

# 发送带图片的消息
async def send_image_message(bot: Bot, target_id: int, is_group: bool, image_path: str):
    """
    发送带图片的消息
    :param bot: 机器人实例
    :param target_id: 目标群号或用户ID
    :param is_group: 是否为群消息
    :param image_path: 图片路径
    """
    try:
        # 读取图片并转换为base64
        with open(image_path, "rb") as f:
            image_data = f.read()
        image_b64 = image_data.encode("base64").replace("\n", "")
        
        # 构造图片消息
        image_msg = MessageSegment.image(f"base64://{image_b64}")
        
        if is_group:
            await bot.send_group_msg(group_id=target_id, message=image_msg)
            print(f"已向群 {target_id} 发送图片: {image_path}")
        else:
            await bot.send_private_msg(user_id=target_id, message=image_msg)
            print(f"已向用户 {target_id} 发送图片: {image_path}")
    except Exception as e:
        print(f"发送图片消息失败: {str(e)}")

# 命令处理器 - 回复私聊消息
reply_private = on_command("reply_private", rule=to_me(), priority=5)
@reply_private.handle()
async def handle_reply_private(bot: Bot, event: PrivateMessageEvent):
    args = str(event.get_message()).strip()
    if args:
        # 格式: reply_private 用户ID 消息内容
        parts = args.split(" ", 2)
        if len(parts) == 3:
            user_id = int(parts[0])
            message = parts[2]
            await send_private_message(bot, user_id, message)
            await reply_private.finish(f"已向用户 {user_id} 发送消息")

# 命令处理器 - 回复群消息
reply_group = on_command("reply_group", rule=to_me(), priority=5)
@reply_group.handle()
async def handle_reply_group(bot: Bot, event: GroupMessageEvent):
    args = str(event.get_message()).strip()
    if args:
        # 格式: reply_group 群号 消息内容
        parts = args.split(" ", 2)
        if len(parts) == 3:
            group_id = int(parts[0])
            message = parts[2]
            await send_group_message(bot, group_id, message)
            await reply_group.finish(f"已向群 {group_id} 发送消息")

# 定时发送消息示例
async def scheduled_message_sender(bot: Bot):
    """定时发送消息任务"""
    while True:
        # 每天12:00发送消息（示例）
        # current_time = datetime.now().strftime("%H:%M")
        # if current_time == "12:00":
        #     await send_group_message(bot, 123456789, "这是每日定时消息")
        
        # 测试用：每30分钟发送一次
        await asyncio.sleep(1800)

if __name__ == "__main__":
    # 配置文件需要单独创建，这里仅展示核心代码
    # 实际使用时需要创建config.py配置文件
    import nonebot
    from nonebot.adapters.onebot.v11 import Adapter as ONEBOT_V11_Adapter

    # 初始化NoneBot
    nonebot.init()
    app = nonebot.get_asgi()

    # 注册适配器
    driver = nonebot.get_driver()
    driver.register_adapter(ONEBOT_V11_Adapter)

    # 加载插件
    nonebot.load_builtin_plugins("echo")  # 回声插件，用于测试

    # 启动定时任务
    @driver.on_startup
    async def startup_event():
        driver.loop.create_task(scheduled_message_sender(driver.bot))

    # 运行机器人
    if __name__ == "__main__":
        nonebot.run(app="__mp_main__:app")
